package com.fcat.common.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fcat.springboot.mybatis.service.impl.TsuantoneBaseServiceImpl;
import com.fcat.base.common.util.DateUtil;
import com.fcat.base.common.util.StrUtil;
import com.fcat.common.user.entity.UserAudit;
import com.fcat.common.user.mapper.UserAuditMapper;
import com.fcat.common.user.service.UserAuditService;
import com.fcat.common.user.util.AddressUtils;
import com.fcat.common.user.vo.SysLoginLog;
import com.fcat.common.user.vo.UserAuditVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserAuditServiceImpl extends TsuantoneBaseServiceImpl<UserAuditMapper, UserAudit> implements UserAuditService {

    private static Logger logger = LoggerFactory.getLogger(UserAuditServiceImpl.class);

    Map<String, String> logTypeMap = new HashMap<String, String>() {
        {
            put("organizationManage", "组织机构");
            put("userManage", "用户");
            put("monitoredObjectManage", "被监控人员");
            put("deviceManage", "设备");
            put("monitorTask", "监控任务");
            put("systemSetting", "系统设置");
        }
    };

    @Override
    public List<UserAudit> getUserAuditList(Map<String, Object> map) {
        return mapper.selectListByUsername(map);
    }

    @Override
    public UserAudit getOneByUserAuditId(String userAuditId) {
        return mapper.getOneByUserAuditId(userAuditId);
    }

    @Override
    public Integer add(HttpServletRequest request) {
//        String username = request.getHeader("username");
//        String ip = IpUtils.getClientIp(request);
//        String result = null;
//        int num=-1;
//        try {
//            result = AddressUtils.getAddresses("ip=" + ip, "utf-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        if(!StrUtil.isBlank(result)&&!result.equals("0")){
//            UserAudit userAudit = new UserAudit();
//            String url = request.getServletPath();
//            JSONObject json = JSONObject.parseObject(result);
//            JSONObject dataJson = json.getJSONObject("data");
//            String address = dataJson.getString("country") + dataJson.getString("region") + dataJson.getString("city") + dataJson.getString("isp");
//            userAudit.setArea(address);
//            userAudit.setCreateTime(new Date());
//            userAudit.setUsername(username);
//            userAudit.setOptRecord(url);
//            userAudit.setIp(ip);
//            userAudit.setUpdateTime(new Date());
//            num=super.insertSelective(userAudit);
//        }
        UserAudit userAudit = getUserAuditByRequest(request);
        if (userAudit == null || StrUtil.isBlank(userAudit.getOptRecord())) {
            return 0;
        } else {
            return super.insert(userAudit);
        }
    }

    /*
      @param createLog(request,"deviceManage",device.getDeviceId(),"新增");
      logType:日志类型，比如矫正对象管理日志，设备管理日志，登录日志等
      optObject:操作对象，比如矫正对象日志，这里就是矫正对象名称，如果是设备管理日志，这里就是设备名称
      optType：操作类型：新增，删除，修改等
     */
    @Override
    @Async("taskExecutor")
    public Integer createLog(HttpServletRequest request, String logType, String optObject, String optType) {
        UserAudit userAudit = getUserAuditByRequest(request);
        userAudit.setLogType(logType);
        userAudit.setOptObject(optObject);
        userAudit.setOptType(optType);
        Date date = new Date();
        userAudit.setContent("操作人" + userAudit.getUsername() + "在" + DateUtil.formatDate(date, DateUtil.TIME_PATTERN_DISPLAY) + userAudit.getOptType() + "了" + logTypeMap.get(logType));
        userAudit.setCreateTime(date);
        return insert(userAudit);
    }

    @Override
    public UserAudit getUserAuditByRequest(HttpServletRequest request) {
        String username = request.getHeader("username");
        String authorization = request.getHeader("Authorization");
        UserAudit tmpUserAudit = getByUsernameAndToken(username, authorization);
        UserAudit userAudit = new UserAudit();
        String url = request.getServletPath();

        logger.info("tmpUserAudit ："+JSONObject.toJSONString(tmpUserAudit));
        if (tmpUserAudit == null) {
          //   String ip = IpUtils.getClientIp(request);
         //   String ip = request.getHeader("ip");
            String ip = getIpAddr(request);
            logger.info("   登录IP："+ip);
            //logger.error("ip:"+ip);
            String result = null;
            int num = -1;
            if(!StrUtil.isBlank(ip)){
               // result = AddressUtils.getAddresses("ip=" + ip, "utf-8");
                result = AddressUtils.getAlibaba(ip);
            }
            if (!StrUtil.isBlank(result)) {
                //logger.error("+++++++++++++"+result);
                JSONObject json = JSONObject.parseObject(result);
                JSONObject dataJson = json.getJSONObject("data");
                String address = null;
                if (dataJson != null) {
                    address = dataJson.getString("country") + dataJson.getString("region") + dataJson.getString("city") + dataJson.getString("isp");
                } else {
                    logger.error(ip + " ip获取地址失败" + json.toJSONString());
                }
                userAudit.setArea(address);
            }
            userAudit.setIp(ip);
        } else {
            userAudit.setArea(tmpUserAudit.getArea());
            userAudit.setIp(tmpUserAudit.getIp());
        }

        userAudit.setCreateTime(new Date());
        userAudit.setUsername(username);
        userAudit.setOptRecord(url);
        userAudit.setToken(authorization);
        userAudit.setUpdateTime(new Date());
        return userAudit;
    }

    /**
     * 获取登录用户的IP地址
     *
     * @param request HttpServletRequest
     * @return String
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

    @Override
    public UserAudit getByUsernameAndToken(String username, String token) {
        return mapper.getByUsernameAndToken(username, token);
    }

    @Override
    public List<SysLoginLog> getSysLoginLogList(Map<String, Object> map) {
        return mapper.getSysLoginLogList(map);
    }

    @Override
    public List<UserAuditVO> getLogList(Map<String, Object> map) {
        return mapper.getLogList(map);
    }

    @Override
    public List<UserAuditVO> getLast2LoginLog(String username) {
        return mapper.getLast2LoginLog(username);
    }

    @Override
    @Async("taskExecutor")
    public void saveLoginLog(HttpServletRequest request, JSONObject jsonObject, String username, String content) {
        UserAudit userAudit = getUserAuditByRequest(request);
        userAudit.setUsername(username);
        userAudit.setToken(jsonObject.getString("data"));
        userAudit.setContent("登录成功");
        userAudit.setLogType("systemLogin");
        userAudit.setOptType("登录");
        userAudit.setCreateTime(new Date());
        UserAudit result = getByUsernameAndToken(userAudit.getUsername(), userAudit.getToken());
        if (result == null) {
            insert(userAudit);
        } else {
            result.setCreateTime(new Date());
            updateById(result);
        }
    }

}